package com.eastdigit.system.service;

import com.eastdigit.system.model.Constants;
import com.eastdigit.util.DateUtil;
import com.eastdigit.util.PubFun;
import com.eastdigit.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Service
public class FileService implements IFileService {

    public String saveFile(MultipartFile file, String uploadDir) throws Exception {
        String fileName = file.getOriginalFilename();
        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

        String fileType = "file";
        if (",gif,jpg,jpeg,png,bmp,".contains("," + fileExt + ",")) {
            fileType = "image";
        } else if (",swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,".contains("," + fileExt + ",")) {
            fileType = "media";
        }
        if (StringUtil.isEmpty(uploadDir)) {
            uploadDir = fileType;
        }

        String timestamp = DateUtil.getCurrentDate().replace("-", "") + "/";
        String savePath = Constants.ATTACHMENT_PATH + "/" + uploadDir + "/" + timestamp;

        File savedir = new File(savePath);
        if (!savedir.exists()) {
            savedir.mkdirs();
        }
        String newFileName = PubFun.getUUID() + "." + fileExt;
        FileOutputStream fs = new FileOutputStream(savePath + newFileName);
        byte[] bytes = file.getBytes();
        fs.write(bytes);
        fs.close();
        return uploadDir + "/" + timestamp + newFileName;
    }

    public static void download(HttpServletResponse response, String fullPath, String fileName) {
        response.setContentType("text/html;charset=UTF-8");

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        String contentType = "application/octet-stream";
        try {
            response.setContentType(contentType);
            response.setHeader("Content-disposition", "attachment; filename="
                    + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
            byte[] buff = new byte[2048];
            bis = new BufferedInputStream(new FileInputStream(fullPath));
            bos = new BufferedOutputStream(response.getOutputStream());
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (IOException e) {
        } finally {
            try {
                if (bis == null) {
                    bis.close();
                }
                if (bos == null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public String getFileType(String type, String name) {
        if ("application/msword".equals(type)) {
            type = "doc";
        } else if ("application/vnd.openxmlformats-officedocument.wordprocessingml.document".equals(type)) {
            type = "docx";
        } else if ("application/vnd.ms-excel application/x-excel".equals(type)) {
            type = "xls";
        } else if ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".equals(type)) {
            type = "xlsx";
        } else if ("application/vnd.ms-powerpoint".equals(type)) {
            type = "ppt";
        } else if ("application/vnd.openxmlformats-officedocument.presentationml.presentation".equals(type)) {
            type = "pptx";
        } else if ("application/vnd.ms-powerpoint".equals(type)) {
            type = "pps";
        } else if ("application/vnd.openxmlformats-officedocument.presentationml.slideshow".equals(type)) {
            type = "ppsx";
        } else if ("application/pdf".equals(type)) {
            type = "pdf";
        } else if ("application/x-shockwave-flash".equals(type)) {
            type = "swf";
        } else if ("pplication/octet-stream".equals(type)) {
            if (name != null && name.endsWith(".rar")) {
                type = "rar";
            } else {
                type = "exe";
            }
        } else if ("application/x-tar".equals(type) || "application/x-compressed".equals(type)
                || "application/x-zip-compressed".equals(type) || "application/x-compress".equals(type)) {
            type = "rar";
        } else if ("audio/wav".equals(type)) {
            type = "wav";
        } else if ("audio/x-ms-wma".equals(type)) {
            type = "wma";
        } else if ("video/x-ms-wmv".equals(type)) {
            type = "wmv";
        } else if ("audio/mpeg".equals(type)) {
            type = "mp3";
        } else if ("application/vnd.rn-realmedia".equals(type)) {
            type = "rm";
        } else if ("audio/mid".equals(type)) {
            type = "mid";
        } else if ("image/bmp".equals(type)) {
            type = "bmp";
        } else if ("image/gif".equals(type)) {
            type = "gif";
        } else if ("image/png".equals(type)) {
            type = "png";
        } else if ("image/tiff".equals(type)) {
            type = "tif";
        } else if ("image/jpeg".equals(type)) {
            type = "jpg";
        } else if ("text/plain".equals(type)) {
            type = "txt";
        } else if ("text/xml".equals(type)) {
            type = "xml";
        } else if ("text/html".equals(type)) {
            type = "html";
        } else if ("text/css".equals(type)) {
            type = "css";
        } else if ("text/javascript".equals(type)) {
            type = "js";
        } else if ("message/rfc822".equals(type)) {
            type = "mht";
        } else {
            type = "unknown";
        }
        return type;
    }
}
